package com.campus.counseling.controller;

import com.campus.counseling.entity.ChatAnalysis;
import com.campus.counseling.entity.MentalHealthWarning;
import com.campus.counseling.service.ChatAnalysisService;
import com.campus.counseling.service.LSTMAnalysisService;
import com.campus.counseling.service.MentalHealthWarningService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/emotion")
@RequiredArgsConstructor
public class EmotionController {

    private final ChatAnalysisService chatAnalysisService;
    private final LSTMAnalysisService lstmAnalysisService;
    private final MentalHealthWarningService mentalHealthWarningService;

    @PostMapping("/analyze")
    public ResponseEntity<Map<String, Object>> analyzeEmotion(@RequestBody Map<String, Object> request) {
        try {
            log.info("开始情感分析请求处理: {}", request);
            
            // 参数校验
            if (request == null || !request.containsKey("content") || !request.containsKey("userId")) {
                throw new IllegalArgumentException("缺少必要参数: content或userId");
            }

            String content = String.valueOf(request.get("content"));
            Long userId = Long.valueOf(String.valueOf(request.get("userId")));
            Long messageId = request.containsKey("messageId") ? 
                Long.valueOf(String.valueOf(request.get("messageId"))) : null;
            
            // LSTM分析
            log.info("开始LSTM分析, content: {}", content);
            BigDecimal lstmScore = lstmAnalysisService.analyzeChatContent(Collections.singletonList(content));
            log.info("LSTM分析完成, score: {}", lstmScore);
            
            // 生成预警
            log.info("开始生成预警");
            MentalHealthWarning warning = mentalHealthWarningService.analyzeAndGenerateWarning(
                userId,
                Collections.singletonList(content)
            );
            log.info("预警生成完成: {}", warning);
            
            // 保存分析结果
            log.info("开始保存分析结果");
            chatAnalysisService.saveAnalysisResult(
                userId,
                messageId,
                lstmScore,
                warning.getWarningLevel().toString()
            );
            
            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("score", warning.getRiskScore().doubleValue());
            response.put("lstmScore", lstmScore.doubleValue());
            response.put("riskLevel", warning.getWarningLevel().toString());
            response.put("message", "分析成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("情感分析失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    @GetMapping("/history")
    public ResponseEntity<List<ChatAnalysis>> getEmotionHistory(@RequestParam Long userId) {
        log.info("获取情感分析历史，用户ID: {}", userId);
        try {
            List<ChatAnalysis> history = chatAnalysisService.findByUserId(userId);
            log.info("获取到 {} 条历史记录", history.size());
            return ResponseEntity.ok(history);
        } catch (Exception e) {
            log.error("获取情感分析历史失败: ", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    @GetMapping("/realtime")
    public ResponseEntity<Map<String, Object>> getRealtimeEmotion(@RequestParam Long userId) {
        log.info("获取实时情感分析，用户ID: {}", userId);
        try {
            // 改用 MentalHealthWarning 的最新记录
            MentalHealthWarning latestWarning = mentalHealthWarningService.getLatestWarning(userId);
            log.info("获取到最新预警记录: {}", latestWarning);
            
            Map<String, Object> response = new HashMap<>();
            if (latestWarning != null) {
                response.put("score", latestWarning.getRiskScore());
                response.put("lstmScore", latestWarning.getLstmScore());
                response.put("riskLevel", latestWarning.getWarningLevel().toString());
                response.put("timestamp", latestWarning.getCreateTime());
            } else {
                log.info("未找到预警记录，返回默认值");
                response.put("score", 0.5);
                response.put("lstmScore", 0.5);
                response.put("riskLevel", "LOW");
                response.put("timestamp", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取实时情感分析失败: ", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
}